<template>
  <!-- pages/login/login.wxml -->
  <view class="login-container">
    <!-- 修改甲方名称和图标布局 -->
    <view class="client-name">
      <image class="company-icon" src="/static/images/login/cssc.png" mode="aspectFit"></image>
      <view class="client-title dark-variant-100">大连船舶重工集团有限公司</view>
    </view>

    <!-- 泡泡动效背景 -->
    <view class="background-animation">
      <view class="bubble"></view>
      <view class="bubble"></view>
      <view class="bubble"></view>
    </view>

    <!-- 登录卡片 -->
    <view class="login-card" :animation="animationData">
      <view class="title">设备设施运维管理平台</view>

      <view class="input-group">
        <input class="input-item" type="text" v-model="userId" placeholder="请输入工号/用户名"/>
        <input class="input-item" type="number" :password="true" v-model="password" placeholder="请输入密码"/>
      </view>

      <view class="btn-area">
        <!-- <button class="login-btn" @tap="handleLogin">登录系统</button> -->
<!--        				<button class="login-btn" @tap="handleLoginInspur">登录系统</button>-->
        <button class="login-btn" @tap="handleLoginToInspur">登录系统</button>
      </view>

      <view class="footer-links">
        <!-- usedAlone 独立使用checkbox -->
        <up-checkbox usedAlone v-model:checked="isRecord" label="是否记住账号？"></up-checkbox>
      </view>
    </view>

    <!-- 底部软件公司名称和图标 -->
    <view class="company-name">
      <image class="provider-icon" src="/static/images/login/JZ.png" mode="aspectFit"></image>
      <text class="dark-variant-100">镇江市金舟软件有限责任公司</text>
    </view>

    <canvas type="2d" id="animCanvas" class="animation-canvas"></canvas>
  </view>
</template>

<script>
// pages/login/login.js
import {
  saveUserInfo,
  getUserInfo,
  removeUserInfo,
  saveUserLoginRememberInfo,
  getUserLoginRememberInfo,
  removeUserLoginRememberInfo
} from '../../common/login/login.js';
import {
  signInRequest,
  rsaEncrypt,
  isBankObj
} from '../../common/commonUnits.js'; // 引入新的登录方法
import {
  jsonString
} from '../../uni_modules/uview-plus/libs/function/test.js';


export default {
  data() {
    return {
      userId: '',
      password: '',
      isRecord: false,
      loginCount: 0,
      loginCardAnimation: null,
      bubbleAnimations: [],
      animationData: '',
      apiKey: '48ddc0b3-cbc4-2f33-004f-6c02cdb00c83',
    };
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad(options) {
    //记住密码
    var userLoginRememberInfo = getUserLoginRememberInfo();
    this.userId = userLoginRememberInfo.userId;
    this.password = userLoginRememberInfo.password;
    this.isRecord = userLoginRememberInfo.isRecord;
    // 创建动画实例
    this.loginCardAnimation = uni.createAnimation({
      duration: 1000, //动画持续时间
      timingFunction: 'ease' //动画效果 慢-快-慢
    });

    // 创建泡泡动画
    this.createBubbleAnimations();

    // 执行入场动画
    this.showLoginCard();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 获取 canvas 上下文
    const query = uni.createSelectorQuery();
    query
        .select('#animCanvas')
        .fields({
          node: true,
          size: true
        })
        .exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');

          // 设置 canvas 大小
          const dpr = uni.getSystemInfoSync().pixelRatio;
          canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);

          // 开始动画
          // this.startCanvasAnimation(ctx);
        });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },
  methods: {
    //浪潮平台登录
    async handleLoginInspur() {
      if (!this.userId || !this.password) {
        return uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        });
      }

      uni.showLoading({
        title: '登录中...'
      });

      try {
        // 密钥
        const key =
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPpLfSzW7K7ZP1CGL6iUbOHXMtZaiRicIdiNzPDv29DdzSRRHzFhYZRa5FWI7mrIgcDha+eGHHfmoy3JPI0XwfHQ0w9mat6isasBp+ZTQhutkP2BaBGXZKYdVuOOV9TTVL45UTQAIzdJwSsBBDVCeo+xfyxt4gUxxtrdDa+iImWQIDAQAB";
        const encryptPw = rsaEncrypt(this.password, key)
        const signInResTask = signInRequest(this.userId, encryptPw);
        let loginRes;
        signInResTask.onHeadersReceived(({statusCode, header}) => {
          console.log(statusCode)
          loginRes = {
            header:header
          }
        })
        console.log(loginRes)
        const headerLocation = loginRes.header['Location']
        // 登录成功处理  浪潮重定向的地址后包含ssologin
        if (headerLocation.indexOf('ssologin')) {
          // 清除旧缓存
          uni.removeStorageSync('user_info');

          var url =
              'sbssdl/database/v1.0/postout/service/getloginuserinfo'
          //因登录接口不会返回用户详细信息，需要手动获取用户详细信息
          const userDetailRes = await this.$commonUnits.request(
              url, 'PUT', JSON.stringify(this.userId), '48ddc0b3-cbc4-2f33-004f-6c02cdb00c83'
          );
          this.loginCount++;
          if (userDetailRes.statusCode === 200 && userDetailRes) {
            // 合并登录信息和用户详细信息
            const loginInfo = {
              ...userDetailRes.data
            };

            // 保存用户信息
            uni.setStorageSync('user_info', loginInfo);

            // TODO 获取用户权限
            // const permissionRes = await this.$commonUnits.postRequest(
            // 	'sbby.userinformationbiz.getUserInformationByNameId.mobile', {
            // 		nameid: this.userId
            // 	});
            // uni.setStorageSync('user_permission', permissionRes.result);

            // TODO 获取用户数字签名
            // const signatureRes = await this.$commonUnits.postRequest(
            // 	'sbby.userinformationbiz.getUserPicFilePathByUserId.mobile', {
            // 		userid: this.userId
            // 	});
            // uni.setStorageSync('user_pic', signatureRes.res.FILE_PATH);

            // 处理记住账号功能
            if (this.isRecord) {
              // debugger
              saveUserLoginRememberInfo({
                'isRecord': this.isRecord,
                'userId': this.userId,
                'password': this.password
              });
            } else {
              removeUserLoginRememberInfo();
            }

            // 更新登录状态
            this.$commonUnits.sharedState.isLogin = true;
            uni.hideLoading();

            // 跳转到首页
            uni.reLaunch({
              url: "/pages/index/index"
            });

          } else {
            this.loginCount++;
            uni.showToast({
              title: '获取登录信息异常！',
              icon: 'none'
            });

          }

        } else {
          uni.showToast({
            title: loginRes.msg || '登录失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },


    // 浪潮平台登录
    handleLoginToInspur() {
      if (!this.userId || !this.password) {
        return uni.showToast({
          title: '请输入用户名和密码',
          icon: 'none'
        });
      }

      const key =
          "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCPpLfSzW7K7ZP1CGL6iUbOHXMtZaiRicIdiNzPDv29DdzSRRHzFhYZRa5FWI7mrIgcDha+eGHHfmoy3JPI0XwfHQ0w9mat6isasBp+ZTQhutkP2BaBGXZKYdVuOOV9TTVL45UTQAIzdJwSsBBDVCeo+xfyxt4gUxxtrdDa+iImWQIDAQAB";
      const encryptPw = rsaEncrypt(this.password, key);

      uni.showLoading({
        title: '登录中...'
      });
      let signInResTask = signInRequest(this.userId, encryptPw)

      signInResTask.onHeadersReceived(({statusCode, header,data}) => {
        // 重定向
        if (statusCode === 302 &&
            (header['Location']).indexOf('ssologin') >= 1
        ) {
          uni.showToast({
            title: '登录成功！',
            icon: 'none'
          });
          this.loggingSuccess();
        } else {
          this.loggingError();
        }
        uni.hideLoading();
      })
    },

    loggingSuccess() {
      this.loginCount = 1;
      // 清除旧缓存
      uni.removeStorageSync('user_info');
      var url = 'sbssdl/database/v1.0/postout/service/getloginuserinfo'
      //因登录接口不会返回用户详细信息，需要手动获取用户详细信息
      this.$commonUnits.request(
          url, 'PUT', JSON.stringify(this.userId), '48ddc0b3-cbc4-2f33-004f-6c02cdb00c83'
      ).then((userDetailRes) => {
        if (userDetailRes.statusCode === 200 && userDetailRes) {
          // 合并登录信息和用户详细信息
          const loginInfo = {
            ...userDetailRes.data
          };
          // 保存用户信息
          uni.setStorageSync('user_info', loginInfo);
          // 处理记住账号功能
          if (this.isRecord) {
            // debugger
            saveUserLoginRememberInfo({
              'isRecord': this.isRecord,
              'userId': this.userId,
              'password': this.password
            });
          } else {
            removeUserLoginRememberInfo();
          }
          // 更新登录状态
          this.$commonUnits.sharedState.isLogin = true;

          // 跳转到首页
          uni.switchTab({
            url: "/pages/index/index"
          });
        }

      });

    },

    loggingError() {
      this.loginCount++;

      uni.showToast({
        title: '获取登录信息异常！',
        icon: 'none'
      });

      if (this.loginCount >= 5) {
        uni.showToast({
          title: '登录次数过多，请稍后重试！',
          icon: 'none'
        });
      }
    },

    // 登录卡片入场动画
    showLoginCard() {
      this.loginCardAnimation.opacity(0).translateY(50).step({
        duration: 0
      });
      this.loginCardAnimation.opacity(1).translateY(0).step({
        duration: 800
      });
      this.setData({
        animationData: this.loginCardAnimation.export()
      });
    },

    // 创建泡泡动画
    createBubbleAnimations() {
      const bubbles = [1, 2, 3].map((index) => {
        const animation = uni.createAnimation({
          duration: 3000,
          timingFunction: 'ease-in-out'
        });
        return animation;
      });
      this.setData({
        bubbleAnimations: bubbles
      });
      this.animateBubbles();
    },

    // 泡泡动画循环
    animateBubbles() {
      this.bubbleAnimations.forEach((animation, index) => {
        animation
            .translateY(-300)
            .opacity(0.6)
            .step({
              duration: 1500
            })
            .translateY(0)
            .opacity(0)
            .step({
              duration: 0
            });
        this.setData({
          [`bubbleAnimation${index + 1}`]: animation.export()
        });
      });

      // 循环动画
      setTimeout(() => this.animateBubbles(), 3000);
    },

    startCanvasAnimation(ctx) {
      // 实现复杂的动画效果
    }
  }
};
</script>
<style>
/* pages/login/login.wxss */
.login-container {
  min-height: 100vh;
  background: #252B93;
  /* 使用纯色背景 */
  display: flex;
  flex-direction: column;
  /* 改为纵向布局 */
  justify-content: center;
  /* 保持居中对齐 */
  align-items: center;
  padding: 40rpx;
  box-sizing: border-box;
  position: fixed;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

/* 泡泡动效背景 */
.background-animation {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  pointer-events: none;
  overflow: hidden;
  z-index: 0;
  /* 确保在登录卡片下方 */
}

.bubble {
  position: absolute;
  border-radius: 50%;
  background: radial-gradient(circle at 30% 30%, rgba(255, 255, 255, 0.3) 0%, rgba(255, 255, 255, 0.2) 50%, rgba(255, 255, 255, 0.1) 100%);
  box-shadow: 0 2rpx 4rpx rgba(255, 255, 255, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  animation: float-bubble 6s ease-in-out infinite;
  opacity: 0;
}

.bubble:nth-child(1) {
  width: 20rpx;
  height: 20rpx;
  left: 15%;
  animation-delay: 0s;
}

.bubble:nth-child(2) {
  width: 15rpx;
  height: 15rpx;
  left: 45%;
  animation-delay: 2s;
}

.bubble:nth-child(3) {
  width: 18rpx;
  height: 18rpx;
  left: 75%;
  animation-delay: 3.5s;
}

@keyframes float-bubble {
  0% {
    bottom: -50rpx;
    opacity: 0;
    transform: scale(0.8);
  }

  20% {
    opacity: 0.5;
    transform: scale(1);
  }

  80% {
    opacity: 0.3;
    transform: scale(1.2);
  }

  100% {
    bottom: 120%;
    opacity: 0;
    transform: scale(1.4);
  }
}

.login-card {
  width: 90%;
  max-width: 600rpx;
  background: #ffffff;
  /* 改回纯白色背景 */
  border-radius: 25rpx;
  padding: 40rpx 35rpx;
  box-shadow: 0 20rpx 40rpx rgba(0, 43, 102, 0.15);
  /* 简化阴影效果 */
  box-sizing: border-box;
  position: relative;
  border: none;
  /* 移除边框 */
  animation: floatIn 0.8s ease-out forwards;
  margin: 380rpx auto auto auto;
  /* 从280rpx改为380rpx，进一步增加与甲方名称的间距 */
  z-index: 1;
}

.logo-area {
  text-align: center;
  margin-bottom: 60rpx;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

/* 调整标题的大小 */
.title {
  font-size: 40rpx;
  /* 从44rpx改为40rpx */
  color: #003b90;
  font-weight: bold;
  text-align: center;
  margin: 10rpx 0 50rpx 0;
  /* 从60rpx改为50rpx */
  letter-spacing: 2rpx;
}

.input-group {
  margin-bottom: 50rpx;
}

/* 修改输入框样式，添加磨砂效果 */
.input-item {
  width: 100%;
  height: 85rpx;
  background: rgba(248, 250, 253, 0.8);
  /* 改为半透明背景 */
  backdrop-filter: blur(10px);
  /* 添加磨砂效果 */
  -webkit-backdrop-filter: blur(10px);
  border-radius: 42.5rpx;
  margin-bottom: 25rpx;
  padding: 0 35rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  border: 1rpx solid rgba(232, 239, 248, 0.8);
  /* 边框也改为半透明 */
  color: #333;
  transition: all 0.3s ease;
}

/* 输入框获得焦点时的样式 */
.input-item:focus {
  background: rgba(255, 255, 255, 0.9);
  /* 获得焦点时略微提高不透明度 */
  border-color: rgba(0, 102, 204, 0.5);
  box-shadow: 0 0 0 3rpx rgba(0, 102, 204, 0.1);
  backdrop-filter: blur(15px);
  /* 获得焦点时增加模糊程度 */
  -webkit-backdrop-filter: blur(15px);
}

/* 设置placeholder的样式 */
.input-item::placeholder {
  color: rgba(160, 174, 192, 0.45);
  font-size: 28rpx;
  font-weight: 300;
  letter-spacing: 1rpx;
}

/* 去除输入框的默认外观 */
.input-item {
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.input-item:last-child {
  margin-bottom: 0;
}

.btn-area {
  margin-bottom: min(40rpx, 4vh);
}

.btn-area button {
  width: 100%;
  height: 85rpx !important;
  /* 从90rpx改为85rpx */
  line-height: 85rpx !important;
  /* 从90rpx改为85rpx */
  margin-bottom: 20rpx;
  /* 从25rpx改为20rpx */
  border-radius: 42.5rpx;
  /* 从45rpx改为42.5rpx */
  font-size: 30rpx;
  /* 从32rpx改为30rpx */
  border: none;
  padding: 0 !important;
  display: flex !important;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.login-btn {
  background: linear-gradient(45deg, #003b90, #0066cc) !important;
  color: #fff !important;
  box-shadow: 0 8rpx 20rpx rgba(0, 59, 144, 0.3);
}

.login-btn:active {
  transform: translateY(2rpx);
  box-shadow: 0 4rpx 10rpx rgba(0, 59, 144, 0.2);
}

.footer-links {
  display: flex;
  justify-content: space-between;
  font-size: 24rpx;
  /* 从26rpx改为24rpx */
  color: #666;
  padding: 15rpx;
  /* 从20rpx改为15rpx */
  margin-top: 15rpx;
  /* 从20rpx改为15rpx */
}

.footer-links text {
  color: #003b90;
  padding: 10rpx;
  position: relative;
}

.footer-links text::after {
  content: '';
  position: absolute;
  bottom: 6rpx;
  left: 50%;
  width: 0;
  height: 2rpx;
  background: #003b90;
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.footer-links text:active::after {
  width: 80%;
}

/* 适配小屏幕 */
@media screen and (max-height: 600px) {
  .login-card {
    padding: 30rpx 20rpx;
    margin: 320rpx auto auto auto;
    /* 从220rpx改为320rpx，小屏幕时也保持适当间距 */
  }

  .title {
    margin-bottom: 40rpx;
  }

  .input-group {
    margin-bottom: 30rpx;
  }

  .btn-area {
    margin-bottom: 20rpx;
  }
}

/* 添加公司名称样式 */
.company-name {
  position: fixed;
  bottom: 40rpx;
  left: 0;
  right: 0;
  text-align: center;
  color: rgba(255, 255, 255, 0.8);
  font-size: 26rpx;
  padding: 20rpx;
  letter-spacing: 2rpx;
  z-index: 2;
  /* 确保在最上层 */
}

/* 适配小屏幕 */
@media screen and (max-height: 600px) {
  .company-name {
    bottom: 20rpx;
    font-size: 24rpx;
  }
}

@keyframes floatIn {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 修改 canvas 的定位 */
.animation-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

/* 修改甲方名称和图标样式 */
.client-name {
  position: absolute;
  top: 120rpx;
  /* 从140rpx改为120rpx，让整体稍微上移 */
  left: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #ffffff;
  z-index: 1;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
  padding: 0 30rpx;
}

/* 修改甲方图标大小 */
.company-icon {
  width: 140rpx;
  /* 放大图标 */
  height: 80rpx;
  margin-bottom: 20rpx;
  /* 添加底部间距 */
}

/* 修改甲方名称样式 */
.client-title {
  font-size: 50rpx;
  font-weight: bold;
  letter-spacing: 4rpx;
  white-space: nowrap;
  /* 防止换行 */
}

/* 底部软件公司图标保持原样 */
.provider-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
  vertical-align: middle;
}

/* 适配小屏幕 */
@media screen and (max-height: 600px) {
  .client-name {
    top: 60rpx;
    /* 从80rpx改为60rpx */
  }

  .company-icon {
    width: 100rpx;
    height: 100rpx;
    margin-bottom: 16rpx;
  }

  .client-title {
    font-size: 44rpx;
  }
}
</style>